<?php
/**
 * 消息模块
 * User: Administrator
 * Date: 2020/7/5
 * Time: 14:30
 */

namespace app\wechat\controller;

use app\api\model\WxUser;
use app\common\controller\Frontend;
use app\common\service\Wx;
use app\common\service\WxUserService;
use app\wechat\controller\BaseWx;
use EasyWeChat\Foundation\Application;
use think\Config;
use think\Log;
use think\Request;

class Msg extends BaseWx
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public function index() {
        //验证开发者服务器
        //$this->ckServer();

        // 接收消息处理
        $this->app->server->push(function($message){
            switch ($message['MsgType']) {
                case 'event':
                    $messageEvent = $message['Event'];
                    $messageKey = (isset($message['EventKey']) && !empty($message['EventKey'])) ? $message['EventKey'] : '';
                    $returnInfo = $this->eventHandler($messageEvent, $messageKey, $message);
                    return $returnInfo;
                    break;
                case 'text':
                    /*if ($message['Content'] == '肯德基') {
                        return "<a href='https://mp.weixin.qq.com/s/_q9nIGSlem4R7WOCLZEJdQ'>https://mp.weixin.qq.com/s/_q9nIGSlem4R7WOCLZEJdQ</a>";
                    } elseif ($message['Content'] == '酒店') {
                        return "<a href='https://mp.weixin.qq.com/s/ngRw-uP0KckuED_r4dt5bQ'>https://mp.weixin.qq.com/s/ngRw-uP0KckuED_r4dt5bQ</a>";
                    } elseif ($message['Content'] == '生日') {
                        return "<a href='https://mp.weixin.qq.com/s/ux0YmzZA9AX_ig452U8pqA'>https://mp.weixin.qq.com/s/ux0YmzZA9AX_ig452U8pqA</a>\n<a href='https://mp.weixin.qq.com/s/umwrH1opbuTksnocCTYYpw'>https://mp.weixin.qq.com/s/umwrH1opbuTksnocCTYYpw</a>\n<a href='https://mp.weixin.qq.com/s/ot06c4NC_4bFsUJC9PWBTg'>https://mp.weixin.qq.com/s/ot06c4NC_4bFsUJC9PWBTg</a>";
                    } elseif ($message['Content'] == '曹操出行') {
                        return "<a href='http://cp.jegotrip.com.cn/partners/newAct_verification/index.html?actName=act1&actId=299'>http://cp.jegotrip.com.cn/partners/newAct_verification/index.html?actName=act1&actId=299</a>";
                    } elseif ($message['Content'] == '征文') {
                        return "<a href='https://mp.weixin.qq.com/s/teqx4WjWY9M_qwf03xlpDg'>https://mp.weixin.qq.com/s/teqx4WjWY9M_qwf03xlpDg</a>";
                    } elseif ($message['Content']) {    // 回复有内容
                        return $this->defaultSubscribeContent();
                    }*/
                    return "";

                    break;
                /*case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;*/
                default:
                    return '';
                    break;
            }
        });

        //回复消息
        $response = $this->app->server->serve();
        return $response->send();

    }

    /**
     * 检验开发者服务器
     */
    protected function ckServer()
    {
        $response = $this->app->server->serve();
        return $response->send();
    }

    protected function eventHandler($messageEvent, $eventKey, $message)
    {
        //事件转为小写
        $messageEvent = strtolower($messageEvent);
        switch ($messageEvent) {
            case 'subscribe':
                return $this->subscribeHandler($eventKey, $message);
                break;
            case 'unsubscribe': // 取消订阅事件
                //return $this->unsubscribeHandler($message);
                return "";
                break;
            case 'scan': // 带二维码参数
                //return $this->scanHandler($eventKey, $message);
                return "";
                break;
            case 'click': // 处理菜单点击事件
                return $this->menuClickEventHandler($eventKey, $message);
                break;
            default:
                return "";
                break;
        }
    }

    /**
     * @param $sceneStr
     * @param $message
     * @return string
     */
    private function subscribeHandler($sceneStr, $message)
    {
        // 注册
        $this->wxRegister($message);

        /*if ($sceneStr == 'qrscene_cc_travel_1') {   // 扫描的是曹操活动带参数的关注二维码
            return $this->defaultCCtravelContent();
        } elseif ($sceneStr == 'qrscene_card') {    //关注无忧黑开
            return $this->defaultSubscribeContent();
        }*/
        // 返回默认关注公众号的回复消息
        return $this->defaultSubscribeContent();
    }

    private function unsubscribeHandler($message)
    {
        //取消关注
        $this->wxRegister($message, 1);

        return "";
    }

    /**
     * 微信注册
     */
    private function wxRegister($message, $isCancel = 0)
    {
        try {
            $openId = $message['FromUserName'];
            $user = $this->app->user->get($openId);
            if (!$user || !$openId) {
                return false;
            }

            //判断用户是否已经存在
            $userOffical = [];
            if ($user && !empty($openId)) {
                $userOffical = WxUserService::findInfoByCondition(['openid' => $openId]);
            }
            $data = [
                'nickname' => empty($user['nickname']) ? "" : $user['nickname'],
                'city' => empty($user['city']) ? "" : $user['city'],
                'province' => empty($user['province']) ? "" : $user['province'],
                'country' => empty($user['country']) ? "" : $user['country'],
                'headimgurl' => empty($user['headimgurl']) ? "" : $user['headimgurl'],
            ];
            if ($userOffical) { //表示用户注册过
                //更新数据
                if (!$userOffical['unionid']) {
                    $data['unionid'] = empty($user['unionid']) ? "" : $user['unionid'];
                }
                WxUserService::saveById($userOffical['id'], $data);
            } else {    //注册
                $data['openid'] = $openId;
                $data['unionid'] = empty($user['unionid']) ? "" : $user['unionid'];
                WxUserService::addRecord($data);
            }

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * @param $sceneStr
     * @param $message
     * @return string
     */
    private function scanHandler($sceneStr, $message)
    {
        // 注册
        $this->wxRegister($message);

        /*if ($sceneStr == 'cc_travel_1') {   // 扫描的是曹操活动带参数的关注二维码
            return $this->defaultCCtravelContent();
        } elseif ($sceneStr == 'card') {    //关注无忧黑开
            return $this->defaultSubscribeContent();
        }
        // 返回默认关注公众号的回复消息
        return $this->defaultSubscribeContent();*/
    }

    /**
     * 菜单栏中type为click的按钮才会发送return的消息回去
     * eventKey是设置菜单时type为click的key值
     * $message是消息对象
     */
    private function menuClickEventHandler($eventKey, $message)
    {
        /*switch ($eventKey) {
            case 'cc_travel':
                return $this->defaultCCtravelContent();
                break;
            case 'zx_customer':
                return $this->zxCustomerContent();
                break;
            case 'sw_click':
                return $this->businessCooperation();
                break;
            default:
                return "";
                break;
        }*/
        return "";
    }

    private function defaultSubscribeContent()
    {
        /*$link = config('base.html5_host')."/?fromChannel=0";
        return "尊贵的用户，恭候多时，欢迎免费享用精选权益！\n\n星巴克肯德基哈根达斯3折起  -> <a href='".config('base.html5_host')."/?fromChannel=0'>限时开卡赠送礼品</a>\n\n参与立领10元京东E卡-> <a href='https://mp.weixin.qq.com/s/Vd1qAUaHS49BIpDDGSXD2w'>立即参与</a>\n\n小小见面礼，不成敬意，佣金好礼等你拿-> <a href='".config('base.html5_host')."/?fromChannel=0'>戳我领佣金</a>";*/
        return "";
    }

    public function test()
    {
        //签约项目通知
        $msgId = "ViZ4XOU73Hy71kBtyR0tKIWsKCqs4JBavhmbeR1wZ2c";
        //$openId = "o0DnJwORJjHDvTZ7U3gbtiHMzG5o";
        //韦震
        $openId = "o0DnJwG1vjxUbwsjo_s2k15KyOt4";
        //发送订阅消息
        $result = $this->app->template_message->send([
            'touser' => $openId,
            'template_id' => $msgId,
            'url' => '',
            'miniprogram' => [
                'appid' => 'wx16e83bf32072d119',
                'pagepath' => '',
            ],
            'data' => [
                'first' => '测试',
                'keyword1' => '哈哈',
                'keyword2' => 'asfsd',
                'remark' => '备注'
            ],
        ]);
        var_dump($result);
        exit;
    }

    /**
     * 设置菜单
     */
    public function setMenu()
    {
        $buttons = [
            [
                "type" => "miniprogram",
                "name" => "大象云职",
                "url"  => "http://",
                'appid' => 'wx16e83bf32072d119',
                'pagepath' => 'pages/user/home/home'
            ],
            [
                "type" => "view",
                "name" => "优惠",
                "url"  => "https://m.jingxi.com/shopv2/jxpage?venderId=10550041&shopId=10336921&_fd=jdm&jxsid=16045660064950445075"
            ],
            /*[
                "name"       => "咨询客服",
                "sub_button" => [
                    [
                        "type" => "click",
                        "name" => "商户合作",
                        "key"  => "sw_click"
                    ],
                    [
                        "type" => "view",
                        "name" => "了解黑卡",
                        "url"  => "https://mp.weixin.qq.com/s/GW7m7tqzVW5FvmNU2Q7EAA"
                    ],
                    [
                        "type" => "click",
                        "name" => "咨询客服",
                        "key"  => "zx_customer"
                    ]
                ],
            ]*/
        ];
        $setRes = $this->app->menu->create($buttons);
        echo json_encode($setRes, JSON_UNESCAPED_UNICODE);
    }

}